package com.jc.nio.thread;

import java.io.IOException;
import java.net.Socket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.security.acl.Group;
import java.util.Iterator;

/**
 * 连接器<br/>
 * 这是一个连接器线程类，负责将连接的socket交符给woker去处理
 * 
 * @author Joeson
 * @since 2014/05
 * @version 01
 * 
 */
public class Acceptor implements Runnable
{
	/**
	 * 客户端的socket
	 */
	private ServerSocketChannel serverSocket;

	private WorkerGroup workerGroup;

	private Selector selector = null;

	private boolean running = true;
	private boolean paused = false;

	public Acceptor(ServerSocketChannel serverSocket, WorkerGroup workerGroup)
	{
		this.serverSocket = serverSocket;
		this.workerGroup = workerGroup;
		try
		{
			selector = Selector.open();

			serverSocket.register(selector, SelectionKey.OP_ACCEPT);
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void run()
	{

		Iterator<SelectionKey> it = null;
		ServerSocketChannel serverSocket = null;

		while (running)
		{
			while (paused)
			{
				try
				{
					Thread.currentThread().sleep(1000);
				} catch (InterruptedException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			try
			{
				if (selector.select() == 0)
					continue;

				it = selector.selectedKeys().iterator();

				while (it.hasNext())
				{

					serverSocket = (ServerSocketChannel) it.next().channel();
					;
					workerGroup.getWorker().addChannel(serverSocket.accept());
					it.remove();
				}
			} catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

//	@Override
//	public void run()
//	{
//		// 是否是运行状态
//		while (running)
//		{
//			// 如果停止的话，那就让当前线程睡眠
//			while (paused)
//			{
//				try
//				{
//					Thread.currentThread().sleep(1000);
//				} catch (InterruptedException e)
//				{
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//			}// end if(paused)
//
//			try
//			{
//				SocketChannel socket = serverSocket.accept();
//
//				if (running && !paused && socket != null)
//				{
//					// 将通道注册到worker中交给worker处理就行了
//					workerGroup.getWorker().addChannel(socket);
//				}
//			} catch (IOException e)
//			{
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//
//		}
//
//	}

	/**
	 * 暂停当前的acceptor线程
	 */
	public void paused()
	{
		paused = true;
	}
}
